import OrderUpdateModal from '@/pages/Order/components/OrderUpdateModal'
import { getUserList, getUserListByRoleKey } from '@/services/admin/user'
import { getCustomerChannelList } from '@/services/CustomerChannelService'
import {
  CustomerQueryDTO,
  CustomerVO,
  FollowOptionType,
  getCustomerPage,
  getFollowOptions,
  removeCustomer,
} from '@/services/CustomerService'
import { OrderUpdateDTO, OrderVO, saveOrder } from '@/services/OrderService'
import { rangePresets } from '@/utils/DateRangeUtils'
import { convertEnum } from '@/utils/tableUtil'
import { useAccess } from '@@/exports'
import { ProColumns, ProFormSelect, ProTable } from '@ant-design/pro-components'
import { ColumnsState } from '@ant-design/pro-table/es/Store/Provide'
import { useModel } from '@umijs/max'
import { useRequest } from 'ahooks'
import { Button, message, Popconfirm, Space } from 'antd'
import { Tag } from 'antd/lib'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import { useLocalStorage } from 'react-use'

export interface CustomerProps {
  onSave?: () => void
  onUpdate: (record: CustomerVO) => void
  tableRef?: any
}

const Customer = (props: CustomerProps) => {
  const access = useAccess()
  const [columnsState, setColumnsState] = useLocalStorage<Record<string, ColumnsState>>('customerTableColumnsState')
  const { getDictEnum } = useModel('dict')
  const [followType, setFollowType] = useState<FollowOptionType[]>()
  const [channelEnum, setChannelEnum] = useState({})
  const { data: sellerList } = useRequest(async () => {
    return getUserListByRoleKey('seller')
  })
  const { data: operatorList } = useRequest(async () => {
    return getUserList()
  })
  // 创建订单
  const [order, setOrder] = useState<OrderVO>()
  const [createOrderModal, setCreateOrderModal] = useState(false)
  const onCreateOrderModalOpenChange = (state: boolean) => {
    if (state) {
      setCreateOrderModal(true)
    } else {
      setCreateOrderModal(false)
    }
  }
  /**
   *  获取渠道枚举对象
   */
  const getChannelEnum = async () => {
    let channelList = await getCustomerChannelList()
    let reduce = channelList.reduce((acc, curr) => {
      // @ts-ignore
      acc[curr.id] = { text: curr.channelName, status: curr.color }
      return acc
    }, {})
    setChannelEnum(reduce)
  }
  /**
   * 点击创建订单按钮的事件
   * @param record
   */
  const onClickCreateOrderBtn = (record: CustomerVO) => {
    // 初始化订单参数
    setOrder({
      customerId: record.id,
      customerName: record.name,
      sellerId: record.sellerUserId,
      sellerName: record.sellerUserName,
      photoType: record.photoType,
    } as OrderVO)
    setCreateOrderModal(true)
  }
  const onCreateOrderFinish = async (formData: any) => {
    let dto: OrderUpdateDTO = JSON.parse(JSON.stringify(formData))
    dto.arrears = dto.realPrice - dto.alreadyPay
    saveOrder(dto).then(message.success('创建订单成功'))
    return true
  }

  /**
   * 处理table查询事件,并异步请求跟进标签数据
   * @param params 请求参数
   * @returns table数据
   */
  const onTableDataRequestHandler = async (params: CustomerQueryDTO) => {
    getFollowOptions(params).then((options) => {
      setFollowType(
        options.map((option) => {
          option.label = `${option.label} (${option.total})`
          return option
        }),
      )
    })
    return getCustomerPage(params)
  }

  useEffect(() => {
    getChannelEnum().then()
  }, [])

  /**
   * 列定义
   */
  const columns: ProColumns<CustomerVO>[] = [
    {
      title: '客户id',
      hideInSearch: true,
      dataIndex: 'id',
      hideInTable: true,
    },
    {
      title: '品牌',
      hideInSearch: true,
      dataIndex: 'brandName',
      width: 80,
    },
    {
      title: '客户名',
      width: 80,
      ellipsis: true,
      dataIndex: 'name',
      fixed: 'left',
    },
    {
      title: '微信号',
      hideInSearch: true,
      ellipsis: true,
      width: 100,
      dataIndex: 'wxId',
    },
    {
      title: '手机号',
      onFilter: true,
      ellipsis: true,
      width: 120,
      dataIndex: 'phone',
    },
    {
      title: '拍摄类型',
      width: 100,
      dataIndex: 'photoType',
      valueType: 'select',
      valueEnum: getDictEnum('photo_type'),
    },
    {
      title: '渠道名',
      onFilter: true,
      valueEnum: channelEnum,
      width: 130,
      dataIndex: 'channelId',
      fieldProps: {
        width: 40,
      },
      render: (_, record) => (
        <Tag key="channelName" color={record.channelTagColor}>
          {record.channelName}
        </Tag>
      ),
    },
    {
      title: '跟进阶段',
      valueEnum: getDictEnum('follow_up_type'),
      renderFormItem: () => {
        return (
          <>
            <ProFormSelect name="followUpStateId" options={followType}></ProFormSelect>
          </>
        )
      },
      width: 130,
      dataIndex: 'followUpStateId',
    },
    {
      title: '创建时间',
      width: 180,
      hideInSearch: true,
      dataIndex: 'createTime',
    },
    {
      title: '日期范围',
      dataIndex: 'startTime',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        presets: rangePresets,
      },
      initialValue: [dayjs().startOf('month'), dayjs().endOf('month')],
      search: {
        transform: (value) => {
          return {
            startTime: value[0] + ' 00:00:00',
            endTime: value[1] + ' 23:59:59',
          }
        },
      },
    },
    {
      title: '录入人',
      ellipsis: true,
      width: 80,
      dataIndex: 'creatorId',
      valueEnum: convertEnum(operatorList, { label: 'userName', value: 'id' }),
    },
    {
      title: '销售',
      width: 80,
      dataIndex: 'sellerUserId',
      valueEnum: convertEnum(sellerList, { label: 'userName', value: 'id' }),
    },
    {
      title: '备注',
      // width: 200,
      hideInSearch: true,
      ellipsis: true,
      dataIndex: 'remark',
    },
    {
      title: '操作',
      render: (_: any, record: CustomerVO) => [
        <Space key="operate">
          {access.hasCustomerUpdatePerm && (
            <Button type="link" size="small" onClick={() => props.onUpdate(record)}>
              编辑
            </Button>
          )}
          {access.hasOrderSavePerm && (
            <Button type="link" size="small" onClick={() => onClickCreateOrderBtn(record)}>
              创建订单
            </Button>
          )}
          {access.hasCustomerRemovePerm && (
            <Popconfirm
              title="确定要删除吗"
              onConfirm={() => {
                removeCustomer(record.id).then()
                props.tableRef.current?.reload()
              }}
              okText="确认"
              cancelText="取消"
            >
              <Button type="link" danger size="small">
                删除
              </Button>
            </Popconfirm>
          )}
        </Space>,
      ],
      fixed: 'right',
      hideInSearch: true,
    },
  ]

  // 工具栏
  let actions = [
    access.hasCustomerSavePerm && (
      <Button key="create" type="primary" onClick={props.onSave}>
        客资录入
      </Button>
    ),
  ]

  const onFormFinishHandler = async (formData: any) => {
    let res = await onCreateOrderFinish(formData)
    if (res) {
      props.tableRef.current.reload()
      return true
    }
    return false
  }
  return (
    <>
      <ProTable
        onColumnsStateChange={setColumnsState}
        columnsStateMap={columnsState}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['20', '50', '100'],
        }}
        search={{
          labelWidth: 65,
          defaultCollapsed: false,
        }}
        columnEmptyText={false}
        defaultSize="small"
        revalidateOnFocus
        actionRef={props.tableRef}
        columns={columns}
        request={onTableDataRequestHandler}
        toolbar={{
          actions: actions,
        }}
        scroll={{ x: 500 }}
        sticky={{ offsetHeader: 55, offsetScroll: 5 }}
      />
      <OrderUpdateModal
        scene="customer"
        order={order}
        onFinish={onFormFinishHandler}
        open={createOrderModal}
        onOpenChange={onCreateOrderModalOpenChange}
      />
    </>
  )
}

export default Customer
